package com.shy.config.util;

import com.alibaba.fastjson2.JSONObject;
import com.shy.config.common.BusinessEnum;
import com.shy.config.common.TokenConstants;
import com.shy.config.model.R;
import com.shy.config.model.SecurityUser;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 拦截器
 */
@Component
public class TokenFilter extends OncePerRequestFilter {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private TokenManager tokenManager;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        /*从请求获取token*/
        String header = request.getHeader(TokenConstants.AUTHORIZATION);
        /*判断token是否为空*/
        if (!StringUtils.hasText(header)) {
            ResponseUtils.write(response, R.failure(BusinessEnum.TOKEN_NOT_EXIST));
            return;
        }
        /*判断token是否以Bearer开头*/
        if (!header.startsWith(TokenConstants.BEARER)) {
            ResponseUtils.write(response, R.failure(BusinessEnum.TOKEN_NOT_ROLE));
            return;
        }
        /*获取token值*/
        String token = header.replaceFirst(TokenConstants.BEARER, "");
        if (!StringUtils.hasText(token)) {
            ResponseUtils.write(response, R.failure(BusinessEnum.TOKEN_NOT_EXIST));
            return;
        }
        /*token是否合法*/
        if (!JWTUtils.verify(token)) {
            ResponseUtils.write(response, R.failure(BusinessEnum.TOKEN_NOT_ROLE));
            return;
        }
        /*token是否有效*/
        if (Boolean.FALSE.equals(stringRedisTemplate.hasKey(TokenConstants.TOKEN_PREFIX + token))) {
            ResponseUtils.write(response, R.failure(BusinessEnum.TOKEN_NOT_VALID));
            return;
        }
        /*获取记住我标识*/
        Boolean rememberMe = Boolean.parseBoolean(request.getHeader("RememberMe"));
        /*刷新token时间*/
        tokenManager.flushTokenTime(token, rememberMe);
        /*解析token的认证用户对象的json字符串*/
        String userJson = JWTUtils.parseJWT(token);
        /*认证用户对象*/
        SecurityUser securityUser = JSONObject.parseObject(userJson, SecurityUser.class);
        // 获取权限
        Set<SimpleGrantedAuthority> authorities = securityUser.getPerms().stream().map(SimpleGrantedAuthority::new).collect(Collectors.toSet());
        // 封装权限
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(securityUser, null, authorities);
        // 放入上下文
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        // 放行
        filterChain.doFilter(request, response);
    }
}
